<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .custom {
    display: flex;
  }

</style>
<template>
  <Card>
    <div>
      <Row style="text-align:left;padding:10px 0;">
        <Col span="12">
          <Input v-model="queryStr" placeholder="类型/品牌/测能类型" @on-enter="query(queryStr)">
            <!--<Button slot="append" icon="ios-search" type="info" @click.native="query(queryStr)"></Button>-->
          </Input>
        </Col>
        <Col span="12" style="text-align:right;">
          <Button type="success" icon="ios-add-circle-outline" @click="add()">新增</Button>
        </Col>
      </Row>
      <Table :loading="spinShow" border :columns="columns7" :data="tableList" size="small"></Table>
      <Row style="text-align:right;padding:10px 0;">
        <Page :total="pageObj.total" size="small" show-elevator :page-size="pageObj.size" @on-change="pageChange" @on-page-size-change="pageSizeChange"></Page>
      </Row>
      <Modal v-model="aeModal.show" :title="aeModal.title" width="1700" height="1440" @on-cancel="cancel" @on-ok="ok"
             :scrollable="true" @on-visible-change="modalChangeStatus">
        <Tabs :value="showTabPanel" type="card" @on-click="TabsClick">
          <TabPane name="oneTab" label="设备信息">
            <DeviceInfoForm ref="refDeviceInfoForm"></DeviceInfoForm>
          </TabPane>
          <TabPane name="twoTab" label="采集项">
            <CollectionForm ref="refDeviceColForm" :collectionData="collectionList"></CollectionForm>
          </TabPane>
          <TabPane name="threeTab" label="脚本代码">
            <ScriptPanel ref="refScript"></ScriptPanel>
          </TabPane>
        </Tabs>
        <div slot="footer" style="text-align: center;">
          <Button type="primary" @click="handleSubmit()" style="width: 300px;" :loading="doSaveLoading">保存</Button>
        </div>
      </Modal>
    </div>
  </Card>
</template>
<script>
  // 1.先使用import导入你要在该组件中使用的子组件
  import DeviceInfoForm from '../type/DeviceInfoForm.vue'
  import CollectionForm from '../type/CollectionForm.vue'
  import ScriptPanel from '../type/ScriptPanel.vue'
  export default {
    components: { DeviceInfoForm, CollectionForm, ScriptPanel },
    data: function () {
      return {
        collectionList: [],
        pageObj: { total: 0, size: 20, index: 0 },
        childObj: {},
        showTabPanel: 'oneTab',
        spinShow: true,
        doSaveLoading: false,
        tableList: [],
        totalElements: 0,
        queryStr: '',
        units: [],
        attributeTypes: [],
        numberTypes: [],
        aeModal: {
          show: false,
          title: '新增'
        },
        columns7: [{
          title: 'ID',
          key: 'id',
          align: 'center'
        }, {
          title: '类型',
          key: 'useType',
          align: 'center'
        }, {
          title: '型号',
          key: 'model',
          align: 'center'
        }, {
          title: '品牌',
          key: 'brand',
          align: 'center'
        }, {
          title: '读取频率',
          key: 'readInterval',
          align: 'center'
        }, {
          title: '操作',
          key: 'action',
          minWidth: 170,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  ghost: true,
                  size: 'small',
                  icon: 'ios-create-outline'
                },
                style: {
                  margin: '2px'
                },
                on: {
                  click: () => {
                    this.childObj = {}
                    this.aeModal.title = '编辑数据'
                    this.$refs.refDeviceInfoForm.formValidate = {}
                    // this.$refs.refDeviceColForm.collectionData = []
                    this.childObj = JSON.parse(JSON.stringify(params.row))
                    this.modalShow()
                    this.collectionList = params.row.iotCollItems
                    this.$refs.refDeviceInfoForm.updateFormdata(params.row)
                    // this.$refs.refDeviceColForm.updateFormdata(params.row)
                    this.$refs.refScript.updateFormdata(params.row)
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  ghost: true,
                  size: 'small',
                  icon: 'ios-trash-outline'
                },
                style: {
                  margin: '2px'
                },
                on: {
                  click: () => {
                    let config = {
                      title: '提示',
                      content: '您确定删除吗？',
                      onOk: () => {
                        this.deleteOne(params.row.id)
                      }
                    }
                    this.$Modal.confirm(config)
                  }
                }
              }, '删除')
            ])
          }
        }]
      }
    },
    created: function () {
      this.list()
    },
    mounted: function () {
    },
    destroyed: function () {
      this.$Message.destroy()
    },
    methods: {
      modalShow: function () {
        this.aeModal.show = true
      },
      modalHide: function () {
        this.aeModal.show = false
      },
      remove: function (index) {
        this.tableList.splice(index, 1)
      },
      ok: function () {
        // this.$Message.info('Clicked ok')
      },
      cancel: function () {
      },
      // 数据list
      list: function () {
        let self = this
        let getData = {
          'size': self.pageObj.size,
          'page': self.pageObj.index,
          'useType_model_brand_plike': self.queryStr
        }
        self.spinShow = true
        window.myapi.devType_list(getData).then(function (res) {
          self.tableList = []
          if (res.data.status === 200) {
            self.tableList = res.data.data.content.reverse()
            self.totalElements = res.data.data.totalElements
            self.pageObj.size = res.data.data.size
            self.pageObj.total = res.data.data.totalElements
          } else {
            let msg = res.data.msg ? res.data.msg : '请求数据失败!'
            self.$Message.error({ content: msg, duration: 5, closable: true })
          }
          self.spinShow = false
        }).catch(function (e) {
          self.tableList = []
          let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 0, closable: true })
          self.spinShow = false
        })
      },
      // 第几页
      pageChange: function (index) {
        let self = this
        self.pageObj.index = index - 1
        self.list()
      },
      // 每页显示多少
      pageSizeChange: function (index) {
        console.log(index)
      },
      // 删除
      deleteOne: function (id) {
        let arr = []
        arr.push(id)
        let postData = arr
        window.myapi.devType_del(postData).then(res => {
          if (res.data.status === 200) {
            this.$Message.error('删除数据成功!')
            this.list()
          } else {
            let msg = res.data.msg ? res.data.msg : '删除数据失败!'
            this.$Message.error(msg)
          }
        }).catch(function (e) {
          let msg = e.response.data.message ? e.response.data.message : '删除数据失败!'
          this.$Message.error({ duration: 0, closable: true, content: msg })
        })
      },
      // 查询
      query: function (str) {
        if (str) {
          this.queryStr = str
        } else {
          this.queryStr = ''
        }
        this.pageObj.index = 0
        this.list()
      },
      // deviceInfoModalSuccess
      deviceInfoModalSuccess: function () {
        let self = this
        self.modalHide()
        self.list()
      },
      // 新增弹窗
      add: function () {
        this.aeModal.title = '新增数据'
        this.modalShow()
        this.childObj = {}
        this.$refs.refDeviceInfoForm.updateFormdata({})
        this.$refs.refDeviceColForm.updateFormdata({})
      },
      // 新增 提交请求
      save: function () {
        let mainData = this.$refs.refDeviceInfoForm.formValidate
        if (mainData.id) {
          delete mainData.id
        }
        // 获取采集项数据
        mainData.iotCollItems = this.collectionList
        // 获取脚本的数据
        mainData.scriptSwitch = this.$refs.refScript.scriptObj.switch
        mainData.script = this.$refs.refScript.scriptObj.codes === '' ? '' : JSON.stringify(this.$refs.refScript.scriptObj.codes)
        // 开始请求loading
        this.doSaveLoading = true
        window.myapi.devType_save(mainData).then(res => {
          if (res.data.status === 200) {
            this.$Message.success('保存成功!')
            this.modalHide()
            this.query()
          } else {
            let msg = res.data.msg ? res.data.msg : '保存失败！'
            this.$Message.error(msg)
          }
        }).catch(function (e) {
          let msg = e.response.data.message ? e.response.data.message : '保存失败!'
          this.$Message.error({ duration: 0, closable: true, content: msg })
        }).finally(() => {
          this.doSaveLoading = false
        })
      },
      // 修改
      upd: function () {
        let mainData = this.$refs.refDeviceInfoForm.formValidate
        // 获取采集数据
        mainData.iotCollItems = this.collectionList
        // 获取脚本的数据
        mainData.scriptSwitch = this.$refs.refScript.scriptObj.switch
        mainData.script = this.$refs.refScript.scriptObj.codes === '' ? '' : JSON.stringify(this.$refs.refScript.scriptObj.codes)
        this.doSaveLoading = true
        window.myapi.devType_upd(mainData).then(res => {
          if (res.data.status === 200) {
            this.$Message.success('保存成功!')
            this.modalHide()
            this.query(this.queryStr)
          } else {
            let msg = res.data.msg ? res.data.msg : '保存失败！'
            this.$Message.error(msg)
          }
        }).catch(function (e) {
          if (e && e.response && e.response.data) {
            let msg = e.response.data.message ? e.response.data.message : '保存失败!'
            this.$Message.error({ duration: 0, closable: true, content: msg })
          }
        }).finally(() => {
          this.doSaveLoading = false
        })
      },
      modalChangeStatus: function (status) {
        if (!status) {
          this.showTabPanel = 'oneTab'
          this.collectionList = []
          // 清空 代码的填写
          this.$refs.refScript.makeDefault()
        }
      },
      // 显示的tab
      showTab: function (chirldData) {
        let self = this
        if (chirldData.objStr) {
          // 存储form里面的数据
          let obj = JSON.parse(chirldData.objStr)
          self.childObj.useType = obj.useType
          self.childObj.model = obj.model
          self.childObj.brand = obj.brand
          self.childObj.readInterval = obj.readInterval
          self.childObj.prol = obj.prol
          if (obj.id !== undefined) {
            self.childObj.id = obj.id
          }
        }
        if (chirldData.arrStr) {
          // 存储form里面的数据
          self.childObj.iotCollItems = JSON.parse(chirldData.arrStr)
          self.childObj.iotCollItems.map((item) => {
            if (item.isGet === 'true' || item.isGet === true) {
              item.isGet = 1
            } else {
              item.isGet = 0
            }
            return item
          })
        }
        self.showTabPanel = chirldData.tab
      },
      // form弹窗
      updSubmitReady: function () {
        let self = this
        self.upd()
      },
      // form弹窗
      saveSubmitReady: function () {
        let self = this
        self.save()
      },
      // 弹窗 确定按钮
      handleSubmit: function () {
        this.$refs.refDeviceInfoForm.$refs.formValidate.validate((valid) => {
          if (valid) {
            sessionStorage.typeDeviceInfo = true
            if (this.childObj.id) {
              this.upd()
            } else {
              this.save()
            }
          } else {
            sessionStorage.typeDeviceInfo = ''
            this.$Message.error('Fail!')
          }
        })
      },
      // 重置
      handleReset: function () {
        this.$refs.refDeviceInfoForm.handleReset('formValidate')
      },
      // tabs点击
      TabsClick: function (name) {
        this.showTabPanel = name
      }
    }
  }

</script>
